#import "RotatingQueue.h"

@implementation RotatingQueue

@synthesize lastInstertedElement;

- (id) initWithCapacity:(int)capacity {
    if (self = [super init]) {
        size = capacity;
        queue = [[NSMutableArray alloc] initWithCapacity:capacity];
        mostRecentItem = capacity - 1;
    }
    return self;
}


/**
 * Inserts an element to the head of the queue, pushing all other elements
 * one position forward.
 * 
 * @param element
 */
- (void) insertElement:(id)element {
    mostRecentItem = [self advancePointer:mostRecentItem];
    if ([queue count] == mostRecentItem) {
        [queue addObject:element];
    }
    else {
        [queue replaceObjectAtIndex:mostRecentItem withObject:element];
    }
}

- (id) getElement:(int)index {
    index = index % size;
    int queueIndex = mostRecentItem - index;
    if (queueIndex < 0) {
        queueIndex += size;
    }
    if (queueIndex < [queue count]) {
        return [queue objectAtIndex:queueIndex];
    }
    else {
        return nil;
    }
}

- (int) size {
    return size;
}

- (void) setSize:(int)pSize {
    self.size = pSize;
}

- (int) advancePointer:(int)oldPointer {
    int pointer = oldPointer + 1;
    if (pointer < size) {
        return pointer;
    }
    else {
        return 0;
    }
}

- (int) count {
    return [queue count];
}

- (id) getLastInsertedElement {
    if ([queue count] < 1) {
        return nil;
    }
    return [queue objectAtIndex:mostRecentItem];
}

- (NSMutableArray *) toList {
    
    NSRange range = NSMakeRange( 0, [queue count]);
    NSArray *subArray = [[queue subarrayWithRange:range] retain];
    NSMutableArray *result = [NSMutableArray arrayWithArray:subArray];
    [subArray release];
    return result;
    
    //return [NSMutableArray arrayWithArray:queue];
}

- (id) lastInstertedElement {
    if ([queue count] < 1) {
        return nil;
    }
    
    return [queue objectAtIndex:mostRecentItem];
}

+ (void) main:(NSArray *)args {
    RotatingQueue * qu = [[[RotatingQueue alloc] initWithCapacity:10] autorelease];
    [qu insertElement:[NSNumber numberWithInt:1]];
    [qu insertElement:[NSNumber numberWithInt:2]];
    [qu insertElement:[NSNumber numberWithInt:3]];
    [qu insertElement:[NSNumber numberWithInt:4]];
    [qu insertElement:[NSNumber numberWithInt:5]];
    [qu insertElement:[NSNumber numberWithInt:5]];
}

- (void) dealloc {
    [queue release];
    [super dealloc];
}

@end
